#include "communication.hpp"
#include <sys/wait.h>
// 服务端

static void getMessage(int fd)
{
    // 3. 编写通信代码（读取/写入数据）
    char buffer[SIZE];
    while (true)
    {
        memset(buffer, '\0', sizeof(buffer));
        ssize_t s = read(fd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            // 读到数据
            //cout << "Client say # " << buffer << endl;
            cout <<"["  << getpid() << "] "<< "client say> " << buffer << endl;
            
        }
        else if (s == 0)
        {
            // 等于零：说明读到文件结尾！
            //cout << "read end of file, client quit, server quit too!" << endl;
            cerr <<"["  << getpid() << "] " << "read end of file, clien quit, server quit too!" << endl;
            break;
        }
        else
        {
            // 读取失败！
            perror("read");
            break;
        }
    }
}

int main()
{

    // 1. 创建管道文件
    if (mkfifo("./fifo.ipc", MODE) < 0)
    {
        perror("mkfifo");
        exit(1);
    }

    // 此后就是通信

    log("创建管道文件成功！", Debug) << "Step 1" << endl;

    // 2. 正常的文件操作（打开文件）
    int fd = open(ipcPath.c_str(), O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        exit(2);
    }

#if 0
    // 3. 编写通信代码（读取/写入数据）
    char buffer[SIZE];
    while(true){
        memset(buffer, '\0', sizeof(buffer));
        ssize_t s = read(fd, buffer, sizeof(buffer)-1);
        if(s>0){
            // 读到数据
            cout << "Client say # " << buffer << endl;
        }else if(s==0){
            // 等于零：说明读到文件结尾！
            cout << "read end of file, client quit, server quit too!" << endl;
            break;
        }else{
            // 读取失败！
            perror("read");
            exit(3);
        }

    }
#endif

    // 多进程版修改
    int nums = 3;
    for (int i = 0; i < nums; i++)
    {
        pid_t id = fork();
        if (id == 0)
        {
            getMessage(fd);
            exit(1);
        }
    }
    for (int i = 0; i < nums; i++)
    {
        waitpid(-1, nullptr, 0);
    }
    close(fd);
    log("关闭管道文件成功！", Debug) << "Step 3" << endl;

    unlink(ipcPath.c_str()); // 通信完毕删除文件！
    log("删除管道文件成功！", Debug) << "Step 4" << endl;

    return 0;
}